package com.kye.express.business.jd.after_sale.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.beloo.widget.chipslayoutmanager.ChipsLayoutManager;
import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatFragment;
import com.kye.express.business.jd.address_select.AddressSelectActivity;
import com.kye.express.business.jd.address_select.AddressSelectLevel;
import com.kye.express.business.jd.after_sale.viewbinder.JDReturnModeTagsViewBinder;
import com.kye.express.business.jd.order_detail.model.JDOrderDetailModel;
import com.kye.express.databinding.FragmentJdAfterSaleReturnBinding;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.lib.view.statuslayout.StatusLayout;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.address.AddressBean;
import com.kye.model.bean.jd.after_sale.JDReturnModesResultBean;
import com.kye.model.bean.jd.order_details.JDGoodsAfterSaleTypeBean;
import com.kye.model.bean.user.User;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.functions.Consumer;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * @author : Joe
 * @version : 1.0
 * @editor : Joe
 * @created : 08/02/2018
 * @updated : 08/02/2018
 * @description : <Description>
 * @update_reason : <UpdateReason>
 */

public class JDAfterSaleReturnModeFragment extends BaseAppCompatFragment implements JDAfterSaleReturnModeConstract.JDAfterSaleReturnModeView, JDReturnModeTagsViewBinder.OnTagsItemListener {

    private final int REQUEST_ADDESS_TAKE = 1000;
    private final int REQUEST_ADDESS_RECEIVE = 2000;
    private final static String TAG_ORDER_INFO = "TAG_ORDER_INFO";
    private final static String TAG_AFTER_SALE_TYPE = "TAG_AFTER_SALE_TYPE";
    private final static String TAG_DESCRIPTION = "TAG_DESCRIPTION";
    private final static String TAG_RETURN_MODE = "TAG_RETURN_MODE";
    private FragmentJdAfterSaleReturnBinding binding;
    private JDAfterSaleReturnModeConstract.JDAfterSaleReturnModePresenter presenter;
    private JDOrderDetailModel orderDetailModel;
    private JDGoodsAfterSaleTypeBean selectedAfterSaleType;
    private String descriptions;
    private User userInfo;
    private MultiTypeAdapter adapter;
    private JDReturnModesResultBean.ResultBean selectedReturnMode;

    private AddressBean selectedProvinceTake;
    private AddressBean selectedCityTake;
    private AddressBean selectedCountryTake;
    private AddressBean selectedTownTake;

    private AddressBean selectedProvinceReceive;
    private AddressBean selectedCityReceive;
    private AddressBean selectedCountryReceive;
    private AddressBean selectedTownReceive;

    private Dialog dialog;

    public static JDAfterSaleReturnModeFragment newInstance(JDOrderDetailModel orderDetailModel, JDGoodsAfterSaleTypeBean selectedAfterSaleType, String descriptions) {
        Bundle args = new Bundle();
        args.putParcelable(TAG_ORDER_INFO, orderDetailModel);
        args.putParcelable(TAG_AFTER_SALE_TYPE, selectedAfterSaleType);
        args.putString(TAG_DESCRIPTION, descriptions);
        JDAfterSaleReturnModeFragment fragment = new JDAfterSaleReturnModeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null) {
            orderDetailModel = getArguments().getParcelable(TAG_ORDER_INFO);
            selectedAfterSaleType = getArguments().getParcelable(TAG_AFTER_SALE_TYPE);
            descriptions = getArguments().getString(TAG_DESCRIPTION);
        } else {
            orderDetailModel = savedInstanceState.getParcelable(TAG_ORDER_INFO);
            selectedAfterSaleType = savedInstanceState.getParcelable(TAG_AFTER_SALE_TYPE);
            descriptions = savedInstanceState.getString(TAG_DESCRIPTION);
        }
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        outState.putParcelable(TAG_ORDER_INFO, orderDetailModel);
        outState.putParcelable(TAG_AFTER_SALE_TYPE, selectedAfterSaleType);
        outState.putString(TAG_DESCRIPTION, descriptions);
        super.onSaveInstanceState(outState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_jd_after_sale_return, container, false);
        presenter = new JDAfterSaleReturnModeConstract.JDAfterSaleReturnModePresenter();
        initViews(view);
        initEvents();
        return view;
    }

    private void initViews(View view) {
        binding = DataBindingUtil.bind(view);
        ChipsLayoutManager spanLayoutManagerHot = ChipsLayoutManager.newBuilder(getActivity())
                .setOrientation(ChipsLayoutManager.HORIZONTAL)
                .build();
        adapter = new MultiTypeAdapter();
        adapter.register(JDReturnModesResultBean.ResultBean.class, new JDReturnModeTagsViewBinder(this));
        binding.returnModes.setLayoutManager(spanLayoutManagerHot);
        binding.returnModes.setAdapter(adapter);
    }

    private void initEvents() {
        RxView.clicks(binding.llErrorNet.btErrorNetRetry)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(binding.llErrorServer.btErrorServerRetry)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        binding.statusLayout.setOnLoadingListener(new StatusLayout.OnLoadingListener() {
            @Override
            public void onLoading() {
                presenter.getReturnModes(orderDetailModel, userInfo);
            }
        });
        RxView.clicks(binding.takeArea)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
//                        AddressSelectActivity.startActivity(getActivity(), REQUEST_ADDESS_TAKE, AddressSelectLevel.ADDRESS_LEVEL_4_TOWN);
                        Intent intent = AddressSelectActivity.newIntent(getActivity(), AddressSelectLevel.ADDRESS_LEVEL_4_TOWN);
                        startActivityForResult(intent, REQUEST_ADDESS_TAKE);
                    }
                });
        RxView.clicks(binding.receiveArea)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
//                        AddressSelectActivity.startActivity(getActivity(), REQUEST_ADDESS_RECEIVE, AddressSelectLevel.ADDRESS_LEVEL_4_TOWN);
                        Intent intent = AddressSelectActivity.newIntent(getActivity(), AddressSelectLevel.ADDRESS_LEVEL_4_TOWN);
                        startActivityForResult(intent, REQUEST_ADDESS_RECEIVE);
                    }
                });
        RxView.clicks(binding.submit)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                       if (checkInput()) {
                           presenter.submit();
                       }
                    }
                });
    }

    @Override
    protected void initData(@Nullable Bundle savedInstanceState) {
        presenter.bind(this);
        updateReturnModeDesc(selectedReturnMode);
    }

    @Override
    public void onUser(User user) {
        userInfo = user;
        binding.statusLayout.showLoadingView();
        binding.setData(orderDetailModel);
    }

    public void updateReturnModeDesc(JDReturnModesResultBean.ResultBean selectedReturnMode) {
        if (selectedReturnMode != null) {
            binding.modeDesc.setVisibility(View.GONE);
        } else {
            binding.modeDesc.setVisibility(View.GONE);
        }
        if (selectedReturnMode == null) {
            return;
        }
        // todo : 服务类型码，上门取件(4)、客户发货(40)、客户送货(7)
        String code = selectedReturnMode.getCode();
        switch (code) {
            case "4":
                binding.contentTakeInfo.setVisibility(View.VISIBLE);
//                binding.contentTakeInfo.setVisibility(View.GONE);
                break;
            case "40":
                binding.contentTakeInfo.setVisibility(View.GONE);
                break;
            case "7":
                binding.contentTakeInfo.setVisibility(View.GONE);
                break;
            default:
                binding.contentTakeInfo.setVisibility(View.GONE);
                break;
        }
    }

    public void updateTakeGoodsAddress(JDReturnModesResultBean.ResultBean selectedReturnMode) {
        if (selectedReturnMode == null) {
            binding.contentTakeInfo.setVisibility(View.GONE);
        } else {
            binding.contentTakeInfo.setVisibility(View.VISIBLE);
        }
    }

    private void updateByReturnMode(JDReturnModesResultBean.ResultBean selectedReturnMode) {
        // todo : 服务类型码，上门取件(4)、客户发货(40)、客户送货(7)
        String code = selectedReturnMode.getCode();
        switch (code) {
            case "4":
                binding.contentTakeInfo.setVisibility(View.VISIBLE);
//                binding.contentTakeInfo.setVisibility(View.GONE);
                break;
            case "40":
                binding.contentTakeInfo.setVisibility(View.GONE);
                break;
            case "7":
                binding.contentTakeInfo.setVisibility(View.GONE);
                break;
            default:
                binding.contentTakeInfo.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    public void getReturnModesSuccess(List<JDReturnModesResultBean.ResultBean> result) {
        binding.statusLayout.showContentView();
        adapter.setItems(result);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void getReturnModesServerFailed(String msg) {
        binding.statusLayout.showErrorServerView();
    }

    @Override
    public void getReturnModesNetFailed(String message) {
        binding.statusLayout.showErrorNetworkView();
    }

    @Override
    public void onTagClicked(JDReturnModesResultBean.ResultBean item) {
        // todo : 服务类型码，上门取件(4)、客户发货(40)、客户送货(7)
        selectedReturnMode = item;
        updateReturnModeDesc(selectedReturnMode);
        updateByReturnMode(selectedReturnMode);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_ADDESS_TAKE && resultCode == Activity.RESULT_OK) {
            ArrayList<AddressBean> selectedAddresses =  data.getParcelableArrayListExtra("data");
            selectedProvinceTake = selectedAddresses.get(0);
            selectedCityTake = selectedAddresses.get(1);
            selectedCountryTake = selectedAddresses.get(2);
            selectedTownTake = null;
            String address;
            if (selectedAddresses.size() == 4) {
                selectedTownTake = selectedAddresses.get(3);
                address = selectedProvinceTake.getName() + selectedCityTake.getName() + selectedCountryTake.getName() + selectedTownTake.getName();
            } else {
                selectedTownTake = null;
                address = selectedCountryTake.getName() + selectedCityTake.getName() + selectedCountryTake.getName();
            }
            binding.takeArea.setText(address);

        } else if (requestCode == REQUEST_ADDESS_RECEIVE  && resultCode == Activity.RESULT_OK) {
            ArrayList<AddressBean> selectedAddresses =  data.getParcelableArrayListExtra("data");
            selectedProvinceReceive = selectedAddresses.get(0);
            selectedCityReceive = selectedAddresses.get(1);
            selectedCountryReceive = selectedAddresses.get(2);
            selectedTownReceive = null;
            String address;
            if (selectedAddresses.size() == 4) {
                selectedTownReceive = selectedAddresses.get(3);
                address = selectedProvinceReceive.getName() + selectedCityReceive.getName() + selectedCountryReceive.getName() + selectedTownReceive.getName();
            } else {
                selectedTownReceive = null;
                address = selectedCountryReceive.getName() + selectedCityReceive.getName() + selectedCountryReceive.getName();
            }
            binding.receiveArea.setText(address);
        }
    }

    private boolean checkInput() {
        if (selectedReturnMode == null) {
            ToastManager.show(getActivity(), "请选择服务类型");
            return false;
        }
        // todo : 服务类型码，上门取件(4)、客户发货(40)、客户送货(7)
        String code = selectedReturnMode.getCode();
        switch (code) {
            case "4": {
                String takeArea = binding.takeArea.getText().toString();
                if (TextUtils.isEmpty(takeArea)) {
                    ToastManager.show(getActivity(), "请选择取货地址");
                    return false;
                }
                String takeAddress = binding.takeAddress.getText().toString();
                if (TextUtils.isEmpty(takeAddress)) {
                    ToastManager.show(getActivity(), "请输入取货详细地址");
                    return false;
                }
                String receiveArea = binding.receiveArea.getText().toString();
                if (TextUtils.isEmpty(receiveArea)) {
                    ToastManager.show(getActivity(), "请选择收货地址");
                    return false;
                }
                String receiveAddress = binding.receiveAddress.getText().toString();
                if (TextUtils.isEmpty(receiveAddress)) {
                    ToastManager.show(getActivity(), "请输入收货详细地址");
                    return false;
                }
                break;
            }
            case "40":
            case "7": {
                String receiveArea = binding.receiveArea.getText().toString();
                if (TextUtils.isEmpty(receiveArea)) {
                    ToastManager.show(getActivity(), "请选择收货地址");
                    return false;
                }
                break;
            }
            default:
                break;
        }
        return true;
    }

    @Override
    public void submitSuccess(OpenApiResult<Object> result) {
        if (getActivity() != null) {
            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
        }
    }

    @Override
    public void submitServerFailed(String msg) {
        ToastManager.show(getActivity(), msg);
    }

    @Override
    public void submitNetFailed(String message) {
        ToastManager.show(getActivity(), message);
    }

    @Override
    public void onLoading() {
        dialog = KyeProgressDialog.show(getActivity(), dialog);
    }

    @Override
    public void onLoaded() {
        KyeProgressDialog.dismiss(dialog);
    }


    @Override
    public FragmentJdAfterSaleReturnBinding getBinding() {
        return binding;
    }

    @Override
    public JDOrderDetailModel getOrderDetailModel() {
        return orderDetailModel;
    }

    @Override
    public JDGoodsAfterSaleTypeBean getSelectedAfterSaleType() {
        return selectedAfterSaleType;
    }

    @Override
    public String getDescriptions() {
        return descriptions;
    }

    @Override
    public User getUserInfo() {
        return userInfo;
    }

    @Override
    public JDReturnModesResultBean.ResultBean getSelectedReturnMode() {
        return selectedReturnMode;
    }

    @Override
    public AddressBean getSelectedProvinceTake() {
        return selectedProvinceTake;
    }

    @Override
    public AddressBean getSelectedCityTake() {
        return selectedCityTake;
    }

    @Override
    public AddressBean getSelectedCountryTake() {
        return selectedCountryTake;
    }

    @Override
    public AddressBean getSelectedTownTake() {
        return selectedTownTake;
    }

    @Override
    public AddressBean getSelectedProvinceReceive() {
        return selectedProvinceReceive;
    }

    @Override
    public AddressBean getSelectedCityReceive() {
        return selectedCityReceive;
    }

    @Override
    public AddressBean getSelectedCountryReceive() {
        return selectedCountryReceive;
    }

    @Override
    public AddressBean getSelectedTownReceive() {
        return selectedTownReceive;
    }
}
